## You need the following if this is ever being run as a script 
import os, sys  
  
sys.path.insert(0, "C:\Documents and Settings\wendy_admin\src\eclipse_workspace\djangodb\main")  
if not os.environ.has_key("DJANGO_SETTINGS_MODULE"):
    os.environ["DJANGO_SETTINGS_MODULE"]="wjContact.settings"
    


from django import newforms as forms

from wjContact.contacts.exceptions import MultiWidgetException


import datetime
import pdb


class EnglishNamesMultiWidget(forms.MultiWidget):
    """
    A Multiwidget with a better 'render' method that gives the individual 
    widgets english-names rather than numbers. Particularly useful when you are
    dealing with lists of repeating fields,where the numbering can become 
    confusing.
    
    So, with a standard Multiwidget, made of two TextInputs (for pet_id and 
    pet_name) and a delete Checkbox, these would end up being called 
    pet_0 (the TextInput for pet_id) and  pet_1(the TextInput for pet_name). 
    The third widget would not be present in form.data unless the user has
    actually checked the box (a wrinkle in how html inputs work.)
    
    So then if you had a RepeatableField list of two of these 'standard' 
    multiwidgets, you would get something like:
    (Pdb) ff.data
    <MultiValueDict: {'pet_2_0': ['new_entry'], 'last_name': ['Name'], 
    'pet_1_1': ['Jesse'], 'first_name': ['New'], 
    'pet_1_0': ['new_entry'], 'pet_2_1': ['Jesse']}>
    
    
    Usage:
    
    You need to give the constituent-widgets a widget_name attribute now when 
    you create them (ie during the Fields __init__ method or when the
    Field() class is called.
    
    widgets = (
                   forms.TextInput(attrs={'widget_name': 'contact_phone_join_id'}), 
                   forms.TextInput(attrs={'widget_name': 'phone_number'}),  
                   ...  ,
                   ...  ,
                )
                
                
    For a DeleteCheckbox you also give it an 'id_suffix' as follows:
                
        PhoneDeleteCheckbox(
            attrs={
                    'widget_name': 'phone_delete', 
                    'id_suffix': 'phone_delete_id'
                    },
                             
    Although the reason for this I have forgotten for the moment! (but IIABDFI).
    
    """
    def render(self, name, value, attrs=None):
        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        #pdb.set_trace()
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
                widget_name = widget.attrs.get('widget_name')          
                if widget_name:
                    ## name is the name of the Field, so the following should
                    ## give something like 'pet_petname' or 'pet_1_petname' if
                    ## this is a multifield/multiwidget.
                    attrs['id'] = name + '_' + widget_name
            except KeyError:
                msg = "key error while trying to render an EnglishNamesMultiWidget." 
                raise KeyError, msg
            output.append(widget.render(name + '_%s' % widget_name, widget_value, attrs))
            ##pdb.set_trace()
        return self.format_output(output)
    
class DeleteCheckbox(forms.widgets.CheckboxInput):
    """ """
    def render(self, name, value, attrs=None):
        output=forms.widgets.CheckboxInput.render(self, name, value, attrs={'id':attrs['id']})
        if 'id' in attrs:
            id = attrs['id']
            label = "<label class=label_for_%s_delete_checkbox for=%s> Delete this entry? </label>" % (attrs['id'], attrs['id'])
        return label + output
    
